package com.fofia.iotweb.web.dbdomain.services.admin;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fofia.iotweb.web.dbdomain.mappers.admin.SysPositionMapper;
import com.fofia.iotweb.web.dbdomain.models.admin.SysPosition;
import com.fofia.iotweb.web.dbdomain.models.admin.SysRole;
import com.fofia.iotweb.web.dbdomain.models.admin.SysUser;
import com.fofia.iotweb.web.dto.DataTableDto;
import com.fofia.iotweb.web.dto.LoginUserDto;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;

@Component
public class SysPositionService {

    @Inject("db")
    private SysPositionMapper positionMapper;

    public DataTableDto getPageList(int page, int psize, String postName){


        QueryWrapper queryWrapper=QueryWrapper.create();
        if(!StrUtil.isEmpty(postName)){
            queryWrapper.where(SysPosition::getPostName).eq(postName);
        }

        queryWrapper.orderBy(SysPosition::getPostSort).asc();

        Page<SysPosition> records=positionMapper.paginate(page,psize,queryWrapper);
        var list=records.getRecords();


        DataTableDto  dto=new DataTableDto();
        dto.setRows(list);
        dto.setTotal(records.getTotalRow());
        dto.setPageNumber(page);
        dto.setPageSize(psize);

        return dto;
    }


    public SysPosition getModel(int id){
        return positionMapper.selectOneById(id);
    }


    public void removeAll(String ids){
        List<Integer> idArray = Arrays.asList(Convert.toIntArray(ids)) ;
        positionMapper.deleteBatchByIds(idArray);
    }

    public void save(SysPosition dto, LoginUserDto loginUserDto){
        if(dto.getPostCode().isEmpty()){
            dto.setPostCode("");
        }

        dto.setUpdateBy(loginUserDto.getLoginName());
        dto.setUpdateTime(DateUtil.date());
        if(dto.getId()==null||dto.getId()==0){
            dto.setCreateBy(loginUserDto.getLoginName());
            dto.setCreateTime(DateUtil.date());
            positionMapper.insert(dto);
            return;
        }

        positionMapper.update(dto);
    }
}
